<template>
    <div class="zs-table-page-container">
        <div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
            <span>
                <el-input clearable :value="biProjectName" class="zs-select-md zs-space-right-sm" placeholder="项目"
                    disabled />
                <el-select v-model="queryParams.accountsId" filterable clearable class="zs-select-md zs-space-right-sm"
                    placeholder="账套名称">
                    <el-option v-for="item in accounts" :key="item.accountsId" :label="item.accountsName"
                        :value="item.accountsId" />
                </el-select>
                <el-date-picker class="zs-space-right-sm" v-model="queryParams.reportMonth" type="month" placeholder="年月"
                    :clearable="false" value-format="YYYY-MM"  :disabled-date="disabledDateStart"/>
                <el-button class="zs-btn-plain" @click="getList()"> 查询 </el-button>
            </span>
            <span class="zs-layout-flex-row">
                <el-button class="zs-btn-plain" @click="handleOpenImportDrawer()"
                    :disabled="queryParams.accountsId.length == 0">
                    <el-icon class="el-icon--left">
                        <Download />
                    </el-icon>导入
                </el-button>
                <el-button class="zs-btn-plain" @click="handleDownload" disabled>
                    <el-icon class="el-icon--left">
                        <Upload />
                    </el-icon>
                    <span>导出</span>
                </el-button>
            </span>
        </div>
        <div class="zs-card zs-table-page-content">
            <hsTableV2 :columns="tableData.cloumns" :data="tableData.data" :expendList="expandedRowKeys" isTree fixed
                expandColumnKey="id" :rowClassFun="tableData.rowClass" :loading="tableData.loading"></hsTableV2>
            <!-- <div class="zs-text-gray-dark zs-text-sm zs-space-top">*单位：万元；元/㎡/月；㎡</div> -->
        </div>
    </div>
    <hsImportData ref="importRef" v-if="isShowImportDrawer" :isShow="isShowImportDrawer" @clickImportBtn="importFile"
        @close="closeImportDrawer" @download="handleDownloadFile" />
</template>
<script setup lang="jsx">
import { queryAccountsApi, queryDetailsApi, impExcelApi } from '@/api/Manage/Business/finance'
import { toThousands } from '@/utils/number-util'
import { downloadOpenFileUrl } from '@/utils/publicUtils'
import { ref, reactive } from 'vue';
import { downloadNewFile } from '@/utils/publicUtils';
import { ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';
let route = useRoute();
let { biProjectCode, biProjectName, yearmonth, subjectType, cardType } = route.query

const disabledDateStart = (date) => {
    return date.getTime() < new Date('2019-01').getTime()
}

const accounts = ref([])

// 查询条件
let queryParams = reactive({
    biProjectCode: biProjectCode,
    accountsId: '',
    reportMonth: yearmonth,
    subjectType: subjectType,
    cardType: cardType
})
const windowWidth = document.documentElement.scrollWidth;
let celWidth = ( windowWidth - 138 - 100 - 160 - 160 - 160 )
const cloumnsFix = [
    {
        key: "id",
        dataKey: "id",
        title: "科目序号",
        align: "left",
        width: 100,
        fixed: true,
        cellRenderer: ({ rowData }) => (
            <div>{rowData.subjectNum}</div>
        )
    },
    {
        key: "subjectName",
        dataKey: "subjectName",
        title: "科目名称",
        width: celWidth,
        fixed: true,
        align: "left",
        cellRenderer: ({ rowData }) => (
            <div style={{whiteSpace: 'pre'}}>{rowData.subjectName}</div>
        )
    },
    {
        key: "val1",
        dataKey: "val1",
        title: "调整前",
        align: "right",
        width: 160,
        fixed: true,
        cellRenderer: ({ rowData }) => (
            <div>{toThousands(rowData.val1)}</div>
        )
    },
    {
        key: "val2",
        dataKey: "val2",
        title: "调整值",
        align: "right",
        width: 160,
        fixed: true,
        cellRenderer: ({ rowData }) => (
            <div>{toThousands(rowData.val2)}</div>
        )
    },
    {
        key: "val3",
        dataKey: "val3",
        title: "调整后",
        align: "right",
        width: 160,
        fixed: true,
        cellRenderer: ({ rowData }) => (
            <div>{toThousands(rowData.val3)}</div>
        )
    }
]
let tableData = ref({
    loading: false,
    data: [],
    cloumns: cloumnsFix,
})

// let curLevelId = ref(0)
let expandedRowKeys = ref([])
const convertToFlatArray = (arr) => {
    arr.map(item => {
        // item.lastStage = item.format_type == 3 ? 1 : 0 // 设置:是否为最后一级 是末级 但不是第一级 变灰色
        // item.lastStage = 0 // 设置:是否为最后一级 0 都改为否 不变色

        item.subjectLevel == 1 || item.subjectLevel == 2 ? expandedRowKeys.value.push(item.id) : '' // 第一级 第二级 默认展开
        // item.subjectLevel == 1 ? curLevelId.value++ : ''
        // item.curParentIndex = curLevelId.value // 设置统一的第一级index， 用于斑马纹

        if (Array.isArray(item.children)) {
            convertToFlatArray(item.children);
        }
        return item
    })
}

const getOptionList = async () => {
    // 账套名称
    let res = await queryAccountsApi(biProjectCode)
    if (res.data.code == 200) {
        accounts.value = res.data.data
    }
    getList()
}
getOptionList()

let test = ref(0)
const getList = () => {
    test.value++
    tableData.value.loading = true
    let params = Object.assign({}, queryParams);
    queryDetailsApi(params).then((res) => {
        if (res.data.code == 200 && res.data.data) {
            convertToFlatArray(res.data.data)
            tableData.value.data = res.data.data
        } else {
            tableData.value.data = []
        }
    }).finally(() => {
        tableData.value.loading = false
    })
}


// 导入
let importRef = ref();
let isShowImportDrawer = ref(false);

function handleOpenImportDrawer() {
    isShowImportDrawer.value = true;
}
function importFile(params) {
    // isLoading.value = true;
    let param = new FormData();
    params.forEach(el => {
        param.append("file", el.file);
    })

    param.append('biProjectCode', queryParams.biProjectCode)
    param.append('accountsId', queryParams.accountsId)
    param.append('reportMonth', queryParams.reportMonth)
    param.append('subjectType', queryParams.subjectType)
    param.append('cardType', queryParams.cardType)

    impExcelApi(param).then(res => {
        if (res.data.code == 200 && res.data.data) {
            ElMessage({
                message: '导入成功',
                type: 'success',
            });
        }
        isShowImportDrawer.value = false
        getList()
        // isLoading.value = false
    })
}
function closeImportDrawer() {
    isShowImportDrawer.value = false;
}
// 下载模版
async function handleDownloadFile() {
	downloadOpenFileUrl(`${process.env.VUE_APP_BASE_API_ZK}/portal-server/v1/api/finReport/downloadExcelTemplate?subjectType=${subjectType}`)
}
// 导出
const handleDownload = async () => {
    const fileName = `品牌坪效分析报表.xls`;
    let fileData;
    // let params = Object.assign({}, queryParams);
    // params.formatCode = formatCodeStr.value
    // await brandFlatEffectListExportApi(params).then(res => {
    //     fileData = res.data;
    // });
    downloadNewFile(fileData, fileName);
};

</script>
<style lang="scss" scoped></style>
